#!/bin/bash

cur_dir=$(pwd)
alb_packages="$cur_dir/alb_packages"
install_package=${1:-"$cur_dir/alb_install_dir"}

check_dir_exists() {
    if [ ! -d $1 ]
    then
        mkdir $1 && echo "未找到目录: $1, 新建目录: $1"
    else
        echo "目录已存在: $1"
    fi
}

check_installed() {
    type "$1" &> /dev/null
    if ! [ $? -eq 0 ]
    then
        echo "$1 is not installed. begin to install $1..."
        $2
    else
        echo "$1 was installed"
    fi
}

update_apt() {
    cp sources.list /etc/apt/sources.list
    apt-get update
}

update_apt_and_install_deps() {
    apt install -y build-essential curl wget perl-base unzip
    wget -qO - https://openresty.org/package/pubkey.gpg | apt-key add -
    apt-get update
    apt-get -y install software-properties-common
    add-apt-repository -y "deb http://openresty.org/package/ubuntu $(lsb_release -sc) main"
    apt-get update
    apt install -y libreadline-dev libpcre3-dev  libssl-dev \
        openresty-openssl111-dev zlib1g-dev libncurses5-dev
}

install_etcd() {
    cd $install_package
    tar -xf $alb_packages/etcd-v3.4.13-linux-amd64.tar.gz
    cd etcd-v3.4.13-linux-amd64
    cp -a etcd etcdctl /usr/bin/
}

install_openresty() {
    cd $install_package
    tar -xzf $alb_packages/openresty-1.19.3.1.tar.gz
    cd openresty-1.19.3.1
    # 配置安装环境（可自行修改安装目录）
    ./configure --prefix=/usr/local/openresty --with-http_stub_status_module --with-ipv6 --with-http_v2_module --with-http_realip_module
    # 编译安装
    make && make install
    # 设置软连接
    ln -s /usr/local/openresty/bin/openresty /usr/bin/openresty
}

install_lua() {
    cd $install_package
    # 解压、编译安装
    tar -zxf $alb_packages/lua-5.1.3.tar.gz
    cd lua-5.1.3
    make linux test && make install
}

install_luarocks() {
    cd $install_package
    # 解压
    tar -xzpf $alb_packages/luarocks-3.6.0.tar.gz
    cd luarocks-3.6.0
    # 配置lua安装目录
    ./configure --with-lua-include=/usr/local/include
    # 编译并安装
    make && make install
}

install_alb () {
    cd $install_package
    tar -xzf $alb_packages/alb.tar.gz
    if [ -f $install_package/alb/logs/nginx.pid ]
    then
        rm $install_package/alb/logs/nginx.pid
    fi
}

install_alb_dashboard() {
    cd $install_package
    tar -xzf $alb_packages/alb-dashboard.tar.gz
}


# 检查安装目录是否存在,不存在则新建
check_dir_exists $install_package

# 先更新源--阿里源
update_apt

# 更新环境依赖make等
update_apt_and_install_deps

# 安装etcd
check_installed "etcd" install_etcd

# 安装openresty
check_installed "openresty" install_openresty

# 安装lua
check_installed "lua" install_lua

# 安装luarocks
check_installed "luarocks" install_luarocks

# 安装alb
install_alb

# 安装alb-dashboard
install_alb_dashboard

# 启动etcd
nohup etcd >> /tmp/etcd_server.log 2>&1 &

# 启动alb
cd $install_package/alb
./bin/alb stop
./bin/alb start

# 启动alb-dashboard
cd $install_package/alb-dashboard/
nohup ./manager-api > /tmp/alb-dashboard.log 2>&1 &

